package persistence;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class PersistenceManager {

	public static final boolean DEBUG = true;

	private static final PersistenceManager instance = new PersistenceManager();

	protected EntityManagerFactory emf;

	public static PersistenceManager getInstance() {
		return instance;
	}

	public static EntityManager getEntityManager() {
		return getInstance().getEntityManagerFactory().createEntityManager();
	}

	private PersistenceManager() {
	}

	public EntityManagerFactory getEntityManagerFactory() {
		if (emf == null)
			createEntityManagerFactory();
		return emf;
	}

	public void closeEntityManagerFactory() {
		if (emf != null) {
			emf.close();
			emf = null;
			if (DEBUG)
				System.out.println("n*** Persistence finished at "
						+ new java.util.Date());
		}
	}

	protected void createEntityManagerFactory() {

		this.emf = Persistence.createEntityManagerFactory("catserv");
		if (DEBUG)
			System.out.println("n*** Persistence started at "
					+ new java.util.Date());
	}
}